package unibz.thaison.iosa;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

import com.sun.jersey.api.NotFoundException;

@Path("/user")
public class UserResource {
	private UserManager manager = UserManager.getInstance();
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public List<User> getUsers() {
		return manager.getAll();
	}

	@GET
	@Path("/count")
	@Produces(MediaType.TEXT_PLAIN)
	public String getCount() {
		return "" + manager.count();
	}

	@GET
	@Path("{userid}")
	@Produces(MediaType.APPLICATION_JSON)
	public User getUser(@PathParam("userid") String userId) {
		User u = manager.get(userId);
		if (u != null) 
			return u;
		else
			throw new NotFoundException("User not found");
	}

	@POST
	@Path("/add")
	@Produces(MediaType.TEXT_HTML)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String addUser(@FormParam("id") String id,
			@FormParam("name") String name,
			@FormParam("status") String status,
			@Context UriInfo uriInfo,
			@Context HttpServletResponse servletResponse) throws IOException {
		User user = manager.get(id);
		if (user != null)
			return "There is a existed user with the same id.\n";
		manager.addUser(new User(id, name, status));
		return "New user was added.\n";
	}
	
	@POST
	@Path("/status")
	@Produces(MediaType.TEXT_HTML)
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String status(@FormParam("id") String id,
			@FormParam("status") String status,
			@Context UriInfo uriInfo,
			@Context HttpServletResponse servletResponse) throws IOException {
		User user = manager.get(id);
		if (user != null) {
			user.setStatus(status);
			return "Done.\n";
		} else
			return "User does not exist.\n";
	}
}